import { asyncRoutes, constantRoutes, notFoundRouter } from '@/routers/index';
import { filterAsyncRoutes, filterKeepAlive } from '@/utils/routers';
import { defineStore } from 'pinia';
import { computed, ref, watch } from 'vue';

const APPLIED_SIGNATURE_KEY = 'applied_route_signature';

/**
 * 从 localStorage 获取已应用的路由签名
 */
function getStoredSignature(): string {
  return localStorage.getItem(APPLIED_SIGNATURE_KEY) || '';
}

/**
 * 保存路由签名到 localStorage
 */
function saveStoredSignature(signature: string): void {
  if (signature) {
    localStorage.setItem(APPLIED_SIGNATURE_KEY, signature);
  } else {
    localStorage.removeItem(APPLIED_SIGNATURE_KEY);
  }
}

/**
 * 权限管理Store
 * @description 用于管理用户路由权限和动态路由生成
 * @author 系统
 * @version 1.0.0
 * @since 2024-01-01
 */
export const usePermissionStore = defineStore(
  'permissionState',
  () => {
    /**
     * 完整路由列表
     * @type {import('vue').Ref<any[]>}
     * @description 包含常量路由和动态路由的完整路由列表
     */
    const routes = ref<any[]>([]);

    /**
     * 动态路由列表
     * @type {import('vue').Ref<any[]>}
     * @description 根据用户权限动态生成的路由列表
     */
    const addRoutes = ref<any[]>([]);

    /**
     * 缓存路由配置
     * @type {import('vue').Ref<Record<string, any>>}
     * @description 存储需要缓存的路由组件配置
     */
    const cacheRoutes = ref<Record<string, any>>({});

    /**
     * 已应用的路由权限签名
     * @type {import('vue').Ref<string>}
     * @description 用于判断是否需要重建路由的签名，持久化到 localStorage
     */
    const appliedSignature = ref<string>(getStoredSignature());

    /**
     * 生成路由
     * @param {string[]} roles - 用户角色数组
     * @returns {Promise<any[]>} 动态路由Promise
     * @description 根据用户角色生成对应的动态路由
     */
    const generateRoutes = (roles: string[]) =>
      new Promise(resolve => {
        // 在这判断是否有权限，哪些角色拥有哪些权限
        let accessedRoutes;
        console.log('生成路由 - 角色权限:', roles);
        if (roles && roles.length && !roles.includes('ADMIN')) {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        } else {
          accessedRoutes = asyncRoutes || [];
        }
        accessedRoutes = accessedRoutes.concat(notFoundRouter);
        routes.value = constantRoutes.concat(accessedRoutes);
        console.log('生成路由完成 - 全部路由数量:', routes.value.length);
        addRoutes.value = accessedRoutes;
        resolve(accessedRoutes);
      });

    /**
     * 清除路由
     * @description 清空所有路由状态，恢复初始状态
     */
    const clearRoutes = () => {
      routes.value = [];
      addRoutes.value = [];
      cacheRoutes.value = {};
    };

    /**
     * 获取缓存路由
     * @returns {Record<string, any>} 缓存路由配置对象
     * @description 获取需要keep-alive的路由组件配置
     */
    const getCacheRoutes = () => {
      cacheRoutes.value = filterKeepAlive(asyncRoutes);
      return cacheRoutes.value;
    };

    /**
     * 设置已应用的路由签名
     * @param {string} signature - 路由签名
     */
    const setAppliedSignature = (signature: string): void => {
      appliedSignature.value = signature;
    };

    /**
     * 清除已应用的路由签名
     */
    const clearAppliedSignature = (): void => {
      appliedSignature.value = '';
    };

    /**
     * 检查是否需要重建路由
     * @param {string} currentSignature - 当前路由签名
     * @param {boolean} isFirstAccess - 是否首次访问
     * @param {boolean} routeNotFound - 路由是否未找到
     * @returns {boolean} 是否需要重建路由
     */
    const shouldRebuildRoutes = (
      currentSignature: string,
      isFirstAccess: boolean,
      routeNotFound: boolean
    ): boolean => {
      const signatureChanged = appliedSignature.value !== currentSignature;
      return signatureChanged || (routeNotFound && isFirstAccess);
    };

    // 监听 appliedSignature 变化，自动持久化
    watch(
      appliedSignature,
      newSignature => {
        saveStoredSignature(newSignature);
      },
      { immediate: true }
    );

    /**
     * 权限路由计算属性
     * @returns {any[]} 完整路由列表
     * @description 返回完整的路由配置
     */
    const permission_routes = computed(() => routes.value);

    /**
     * 缓存路由计算属性
     * @returns {any[]} 需要缓存的路由列表
     * @description 返回需要keep-alive的路由配置
     */
    const keepAliveRoutes = computed(() => filterKeepAlive(asyncRoutes));

    /**
     * 检查并修复路由状态
     * @description 用于页面刷新后检查路由状态是否完整
     */
    const checkAndFixRoutes = (): boolean => {
      // 检查是否有持久化的路由数据
      const hasPersistedData = routes.value.length > 0 || addRoutes.value.length > 0;

      if (hasPersistedData) {
        console.log('检测到持久化路由数据，修复路由状态:', {
          持久化路由数量: routes.value.length,
          动态路由数量: addRoutes.value.length,
          签名: appliedSignature.value
        });
        return true;
      }

      return false;
    };

    return {
      routes,
      addRoutes,
      cacheRoutes,
      appliedSignature,
      generateRoutes,
      clearRoutes,
      getCacheRoutes,
      setAppliedSignature,
      clearAppliedSignature,
      shouldRebuildRoutes,
      permission_routes,
      keepAliveRoutes,
      checkAndFixRoutes
    };
  },
  {
    // 持久化配置
    persist: {
      key: 'permissionState',
      storage: window.localStorage,
      // 持久化部分状态
      paths: ['routes', 'addRoutes', 'appliedSignature']
    }
  }
);
